<template>
  <!--弹出窗-->
  <modal ref="modal_1"
         :title="title"
         :isCloseConfirm="this.editable"
         :fullscreen="this.fullscreen"
         top="3%"
         width="80%"
         :close-on-click-modal="true"
         @modalOpened="opened"
         @modalClose="closed">

    <avue-form :option="option" ref="form" v-model="form" @submit="onSubmit" >
      <template #customerNo v-if="this.editable">
        <el-autocomplete
                style="width: 100%;"
                v-model="form.customerNo"
                :fetch-suggestions="queryCustomerNo"
                placeholder="请输入客户账号"
                :trigger-on-focus="false"
                @select="selectCustomerNo"
                :disabled="hasItem"
                :fit-input-width="true"
        ></el-autocomplete>
      </template>
      <template #customerName v-if="this.editable">
        <el-input v-model="form.customerName" readonly placeholder="请选择客户名称" @click="selectCustomerName" :disabled="hasItem"/>
      </template>
      <template #factoryName v-if="this.editable">
        <el-input v-model="form.factoryName" readonly placeholder="请选择工厂信息" @click="selectFactory"/>
      </template>
      <!--<template #bankName v-if="this.editable">-->
        <!--<el-input v-model="form.bankName" readonly placeholder="请选择银行信息" @click="selectBankInfo" :disabled="hasItem"/>-->
      <!--</template>-->
      <template #serviceName v-if="this.editable">
        <el-input v-model="form.serviceName" readonly placeholder="请选择业务人员" @click="selectServiceName"/>
      </template>

      <!--<template #serviceName v-if="this.editable">-->
        <!--<el-input v-model="form.serviceName" readonly placeholder="请选择业务人员" @click="selectServiceName" :disabled="!!this.form.id"/>-->
      <!--</template>-->
      <template #asnItem>
        <asn-item ref="asnItem" @disabledCommit="disabledCommit" @disabledFiled="disabledFiled"></asn-item>
      </template>
    </avue-form>
    <!--底部按钮块, 默认只有"取消"按钮-->
    <template #footerButton>
      <el-button type="primary" v-if="(permission.asn_main_add || permission.asn_main_edit) && editable"
                 :disabled="btnLoading" @click="this.$refs.form.submit()">确认单据
      </el-button>
      <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
    </template>
    <select-customer  ref="selectCustomer"  @success="setCustomerNo"/>
    <!--<select-service  ref="selectService"  @success="setService"/>-->
    <select-factory  ref="selectFactory"  @success="setFactory"/>
    <!--<select-bank  ref="selectBank"  @success="setBank"/>-->
  </modal>
</template>

<script>
    import { getList, getDetail, add, update, remove } from "@/api/anwise/logistics/asn_main";
    import {remoteList} from '@/api/anwise/customer/customer';
    import { mapGetters } from "vuex";
    import { getDeptTree } from '@/api/system/dept';
    import website from '@/config/website';
    import {Pattern} from "@/utils/validate.js";
    import {dateFormat} from "@/utils/date.js";

    import selectCustomer from '../../order/components/select_customer.vue';
    // import selectService from './select_service.vue';
    import selectFactory from '../../order/components/select_factory.vue';
    import selectBank from '../../order/components/select_bank.vue';
    import asnItem from './asn_item.vue';

    export default {
        components: {
            selectCustomer,
        //     selectService,
            selectFactory,
            selectBank,
            asnItem,
        },
        data() {
            return {
                isEnglish:'1',
                hiddenPrice:'1',
                hasItem:false,
                box:false,
                emits: ["success"],
                editable: false,
                title: "订单信息",
                isCloseConfirm: false,
                fullscreen: false,
                btnLoading: false,
                customer:{
                  salesName:"",
                  remark:"",
                  salesRemark:"",
                },
                form: {},
                query: {},
                loading: true,
                option: {
                    card: true,
                    tabs: true,
                    tabsActive: 1,
                    height: 'auto',
                    calcHeight: 30,
                    labelWidth: 150,
                    menuWidth: 120,
                    submitBtn: false,
                    emptyBtn: false,
                    column: [
                        {
                            label: "ASN编号",
                            prop: "asnNo",
                            type: "input",
                            disabled:true,
                            display:true,
                            span:8,
                            placeholder:'保存后自动生成编号',
                            rules: [{
                                required: false,
                                message: "请输入ASN编号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "客户账号",
                            prop: "customerNo",
                            type: "input",
                            span:8,
                            rules: [{
                                required: true,
                                message: "请选择客户账号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "客户名称",
                            prop: "customerName",
                            type: "input",
                            span:8,
                            rules: [{
                                required: true,
                                message: "请输入客户名称",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "工厂名称",
                            prop: "factoryName",
                            type: "input",
                            span:8,
                            rules: [{
                                required: true,
                                message: "请输入工厂名称",
                                trigger: "blur"
                            }],
                        },
                        // {
                        //     label: "收款方",
                        //     prop: "bankName",
                        //     type: "input",
                        //     readonly:true,
                        //     span:8,
                        //     rules: [{
                        //         required: true,
                        //         message: "请输入收款方",
                        //         trigger: "blur"
                        //     }],
                        // },
                        {
                            label: "送货地址",
                            prop: "deliAddress",
                            type: "input",
                            span:16,
                            readonly:true,
                            rules: [{
                                required: true,
                                message: "请输入送货地址",
                                trigger: "blur"
                            }],
                        },

                        {
                            label: "ASN日期",
                            prop: "asnDate",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:8,
                            rules: [{
                                required: true,
                                message: "请选择ASN日期",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "ASN状态",
                            prop: "asnStatus",
                            type: "select",
                            filterable: true,
                            dicUrl: '/api/blade-system/dict-biz/dictionary?code=asn_status',
                            props: {
                                label: 'dictValue',
                                value: 'dictKey',
                            },
                            dataType: 'string',
                            disabled:true,
                            value:'Draft',
                            rules: [{
                                required: false,
                                message: "请输入ASN状态",
                                trigger: "blur"
                            }],
                            span:8,
                        },
                        {
                            label: "ASN来源",
                            prop: "asnSource",
                            type: "select",
                            filterable: true,
                            dicUrl: '/api/blade-system/dict-biz/dictionary?code=order_source',
                            props: {
                                label: 'dictValue',
                                value: 'dictKey',
                            },
                            dataType: 'string',
                            disabled:true,
                            value:'业务创建',
                            rules: [{
                                required: false,
                                message: "请输入ASN来源",
                                trigger: "blur"
                            }],
                            span:8,
                        },
                        {
                            label: "审核人",
                            prop: "assignUser",
                            type: "input",
                            disabled:true,
                            span:8,
                        },
                        {
                            label: "审核日期",
                            prop: "assignDate",
                            type: "input",
                            disabled:true,
                            span:8,
                        },
                      {
                        label: "操作人员",
                        prop: "createUserName",
                        type: "input",
                        disabled:true,
                        span:8,
                      },
                      {
                        label: "操作时间",
                        prop: "createTime",
                        type: "input",
                        disabled:true,
                        span:8,
                      },

                    ],
                    group: [
                        {
                            icon: 'el-icon-house',
                            label: 'ASN项信息',
                            prop: 'group1',
                            column: [
                                {
                                    label: '',
                                    prop: 'asnItem',
                                    className: 'addPadding',
                                    span: 24,
                                    labelWidth: 0,
                                    formslot: true,
                                    display: true,
                                },
                            ],
                        },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.asn_main_add, false),
                    viewBtn: this.validData(this.permission.asn_main_view, false),
                    delBtn: this.validData(this.permission.asn_main_delete, false),
                    editBtn: this.validData(this.permission.asn_main_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
        },
        methods: {
            setFactory(row) {
                if (row) {
                    this.form.factoryId = row.id;
                    this.form.deliAddress = row.facAddr;
                    this.form.factoryName = row.facName;
                    this.$refs.asnItem.factoryId= row.id;
                }
            },
            selectFactory() {
                if (this.form.customerNo)  {
                    this.$refs.selectFactory.showSelect(this.form.customerId);
                } else {
                    this.$message({
                        type: "error",
                        message: "请先选择客户信息!"
                    });
                }
            },
            disabledFiled(hasItem) {
                this.hasItem = hasItem;
            },
            changeDeliDate(value) {
                let asnItem = this.$refs.asnItem.$refs.tableRef.getTableData().fullData;
                if (asnItem.length > 0) {
                    asnItem.forEach(item => {
                        item.deliDate = value;
                    })
                }
            },
            disabledCommit(data) {
                this.btnLoading = data;
            },
            setBank(row) {
                this.form.bankName = row.companyName;
                this.form.bankId = row.id;
                // this.$refs.asnItem.bankId= row.id;
            },
            selectBankInfo() {
                // this.$refs.asnItem.bankId="";
                if (this.form.customerNo)  {
                    this.$refs.selectBank.showSelect(this.form.customerId,2);
                } else {
                    this.$message({
                        type: "error",
                        message: "请先选择客户信息!"
                    });
                }
            },
            queryCustomerNo(val,cb) {
              this.form.customerName = "";
                this.$refs.asnItem.customerNo="";
                const reg = Pattern.number;
                console.log(reg.test(val));
                if (!reg.test(val)) {
                    this.$message({
                        type: "error",
                        message: "客户账号只能为数字!"
                    });
                    return;
                }

                remoteList(val).then(res => {
                    if (res.data.success) {
                        let customerList = [];
                        res.data.data.forEach(item => {
                            customerList.push({
                                value:item.custNo +" - "+item.custName,
                                customerId: item.id,
                                customerNo: item.custNo,
                                customerName: item.custName,
                                deliAddress:item.custAddr,
                            });
                        })
                        cb(customerList);
                    }
                })
            },
            selectCustomerNo(item) {
                console.log(item);
                this.form.customerId = item.customerId;
                this.form.customerNo = item.customerNo;
                this.form.customerName = item.customerName;
                // this.form.deliAddress = item.deliAddress;
                this.$refs.asnItem.customerNo=item.customerNo;
            },
            setCustomerNo(row) {
              this.form.customerName = "";
              if (row) {
                  this.form.customerId = row.id;
                  this.form.customerNo = row.custNo;
                  this.form.customerName = row.custName;
                  // this.form.deliAddress = row.custAddr;
                  this.$refs.asnItem.customerNo=this.form.customerNo;
                  this.$refs.asnItem.editable = this.editable;
              }
            },
            selectCustomerName() {
              this.$refs.selectCustomer.showSelect();
            },
            async validItemEvent() {
                const $table = this.$refs.asnItem.$refs.tableRef
                let errMap = undefined;
                    await $table.validate().then((err) => {
                        console.log("err:",err)
                        errMap=err;
                    })
                  return errMap;
            },
            async onSubmit(form, done) {
                const $table = this.$refs.asnItem.$refs.tableRef
                let checkasnItem = false;
                 const errMap = await this.validItemEvent();
                  console.log(errMap);
                     if (errMap) {
                         this.$message({
                             type: 'error',
                             message: 'ASN项信息有误！',
                         });
                         checkasnItem = true;
                         done();
                         return;
                     }

                console.log("checkasnItem",checkasnItem);
                if (!checkasnItem) {
                    this.btnLoading = true;
                    form.addList = $table.getInsertRecords();
                    form.updateList = $table.getUpdateRecords();
                    form.deleteList = $table.getRemoveRecords();
                    form.itemList = $table.getTableData().fullData;
                    if (!form.itemList || form.itemList.length < 1) {
                        this.$message({
                            type: 'error',
                            message: '无ASN项信息！',
                        });
                        this.btnLoading = false;
                        return;
                    }
                    console.log(form)
                    update(form).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: "success",
                                message: res.msg || "保存成功!"
                            });
                            setTimeout(() => {
                              this.btnLoading = false;
                              done();
                                this.$refs.modal_1.hide();
                            }, 1000)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.msg || "保存失败!"
                            });
                        }
                    }).catch(err => {
                        console.log(err)
                        done();
                        this.btnLoading = false;
                    })

                }
            },
            show(option) {
                this.title = option.title;
                this.type = option.type;
                this.option.detail = this.type === "view";
                this.editable = this.type !== "view";
                this.customer = {};
                if (option.id) {
                    this.hasItem=true;
                    console.log("option.id");
                    setTimeout(() => {
                        getDetail(option.id).then(res => {
                            if (res.data.success) {
                                this.form = res.data.data;
                                // this.customer.salesName =  this.form.customer.cartonMarkRemark;
                                // this.customer.remark = this.form.customer.prodRemark;
                                // this.customer.salesRemark = this.form.customer.salesRemark;
                                this.$refs.asnItem.setData(this.editable, this.form.asnNo)
                                this.$refs.asnItem.customerNo=this.form.customerNo;
                                this.$refs.asnItem.factoryId= this.form.factoryId;
                                // this.$refs.asnItem.customerId=this.form.customerId;
                                // this.$refs.asnItem.idNo=this.form.idNo;
                                // this.$refs.asnItem.bankId= this.form.bankId;
                                // this.$refs.asnItem.editable = this.editable;
                                // this.$refs.asnItem.salesDate = this.salesDate;
                                // this.form.taxRate = Number(this.form.taxRate)
                                // this.findObject(this.option.column, 'idNo').display = true;
                                // this.findObject(this.option.column, 'version').display = true;

                                // const column =  this.findObject(this.option.column, 'contact');
                                // column.dicData=[];
                                // if (res.data.data.customer.contact1) {
                                //     column.dicData.push({name:res.data.data.customer.contact1});
                                // }
                                // if (res.data.data.customer.contact2) {
                                //     column.dicData.push({name:res.data.data.customer.contact2});
                                // }
                                // if (res.data.data.customer.contact3) {
                                //     column.dicData.push({name:res.data.data.customer.contact3});
                                // }
                                // console.log("column",column);
                            }
                        })
                    }, 500);
                } else {
                    this.form = {}
                    this.form.asnDate = dateFormat(new Date(),"yyyy-MM-dd")
                    this.hasItem=false;

                }

                this.$refs.modal_1.show();
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            opened() {
                console.log("opened")
            },
            closed() {

                this.$emit("success");
            }
        }
    };
</script>

<style>
  /*.addPadding {*/
    /*padding: 20px !important;*/
  /*}*/
</style>
